<!-- src/pages/course/discuss.vue -->
<template>
  <view class="discuss-container">
    <up-navbar title="讨论管理" @rightClick="handleAddDiscuss()" :autoBack="true">
      <template #right>
        <up-icon name="plus" size="20" color="#333"></up-icon>
      </template>
    </up-navbar>
    <up-gap height="10" bgColor="#fff"></up-gap>

    <view class="content">
      <view class="search-container">
        <up-search v-model="D.searchKeyword.value" @custom="D.handleSearch()" placeholder="搜索讨论..."></up-search>
      </view>

      <u-list class="discuss-list">
        <u-list-item v-for="(discuss, index) in D.filteredModels.value" :key="discuss.discussId">
          <view class="discuss-item">
            <view class="discuss-info">
              <text class="discuss-title">{{ discuss.title }}</text>
              <text class="discuss-time">{{ formatDate(discuss.createTime) }}</text>
            </view>

            <view class="actions">
              <u-button 
                size="mini" 
                type="info" 
                plain
                @click="showActionMenu(discuss)"
                class="more-button"
              >
                <u-icon name="more-dot-fill" size="18" color="#666"></u-icon>
              </u-button>
            </view>
          </view>
        </u-list-item>
      </u-list>
    </view>

    <!-- 操作菜单 -->
    <u-action-sheet 
      :show="actionMenuVisible" 
      :actions="actionMenuOptions" 
      @close="actionMenuVisible = false"
      @select="handleActionSelect"
    ></u-action-sheet>

    <!-- 讨论编辑弹窗 -->
    <admin-discuss-modal />
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import "jbecool/jbecool.uniapp.min.js";
import "@/js/common.js";
import D from "@/js/admin/discuss.js";

// 操作菜单相关
const actionMenuVisible = ref(false);
const actionMenuOptions = ref([
  { name: '编辑', value: 'edit' },
  { name: '删除', value: 'delete' }
]);
const selectedDiscuss = ref(null);

// 从其他页面传递参数（例如 courseId）
let courseId = -1;

onLoad((option) => {
  // 获取从课程页面传递过来的courseId参数
  if (option.courseId) {
    courseId = parseInt(option.courseId);
  }
});

// 自定义添加讨论方法，设置创建者和课程ID
const handleAddDiscuss = () => {
  D.modalMode.value = 'add';
  Object.assign(D.currentModel, D.rawModel);
  
  // 设置创建者为当前用户
  const userInfo = uni.getStorageSync('userInfo');
  if (userInfo) {
    try {
      const user = JSON.parse(userInfo);
      D.currentModel.createrId = user.userId || 1;
    } catch (e) {
      console.error('解析用户信息失败:', e);
      D.currentModel.createrId = 1;
    }
  } else {
    D.currentModel.createrId = 1;
  }
  
  // 设置课程ID
  if (courseId !== -1) {
    D.currentModel.courseId = courseId;
  }
  
  D.openPopup();
};

onMounted(async () => {
  // 初始化数据
  D.modelList.value = [];
  D.filteredModels.value = [];
  
  // 加载元数据
  const im = await D.loadMeta();
  if (im.success) {
    // 设置关联ID（例如 courseId）
    if (courseId !== -1) {
      D.rawModel.courseId = courseId;
    }

    // 加载讨论数据
    if (courseId !== -1) {
      await D.loadModels({ where: [{ courseId: courseId }] });
    } else {
      await D.loadModels();
    }
  } else {
    uni.showToast({
      title: "获取讨论元数据失败",
      icon: "error",
    });
  }
});

// 显示操作菜单
const showActionMenu = (discuss) => {
  selectedDiscuss.value = discuss;
  actionMenuVisible.value = true;
};

// 处理操作选择
const handleActionSelect = (e) => {
  const action = e.value;
  if (action === 'edit') {
    // 确保在编辑时也设置 courseId 和 createrId
    if (courseId !== -1) {
      selectedDiscuss.value.courseId = courseId;
    }
    D.handleEditModel(selectedDiscuss.value);
  } else if (action === 'delete') {
    D.handleDeleteModel(selectedDiscuss.value);
  }
  actionMenuVisible.value = false;
};

// 格式化时间
const formatDate = (dateString) => {
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};
</script>

<style scoped>
.discuss-container {
  padding: 20px;
}

.content {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
}

.discuss-list {
  margin-top: 15px;
}

.discuss-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.discuss-item:last-child {
  border-bottom: none;
}

.discuss-title {
  font-size: 16px;
  font-weight: 500;
}

.discuss-time {
  display: block;
  font-size: 14px;
  color: #666;
  margin-top: 4px;
}

.actions {
  display: flex;
  gap: 5px;
}

.more-button {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
}
</style>